<template>
  <view class="login-container">
    <view class="login-header">
      <text class="title">{{ pageTitle }}</text>
    </view>

    <view class="login-form">
      <!-- 手机号输入 -->
      <view class="form-item">
        <input
          v-model="form.phone"
          placeholder="请输入手机号"
          class="input"
          type="number"
          maxlength="11"
        />
      </view>

      <!-- 验证码输入 -->
      <view class="form-item code-item">
        <input
          v-model="form.code"
          placeholder="请输入验证码"
          class="input"
          type="number"
          maxlength="6"
        />
        <button
          class="code-btn"
          :disabled="countdown > 0"
          @click="sendCode"
        >
          {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
        </button>
      </view>

      <button class="submit-btn" @click="handleSubmit" v-if="pageTitle === '手机号登录'">登录</button>
      <button class="submit-btn" @click="bindTap" v-else>绑定手机号</button>

    </view>
    <button class="submit-btn" @click="toshareAi" >跳转页面</button>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {useUserStore } from '@/stores/user'

interface PhoneParams {
  user_id: string;
  phone: string;
  nickname: string;
  access?: string;
  refresh?: string;
  is_wechat_bound?: boolean;
  status:string
}
const API_BASE_URL = 'https://52d47b77.r34.cpolar.top'
const countdown = ref(0)
const pageTitle = ref('手机号登录')
const form = ref({
  phone: '',
  code: ''
})
const toshareAi = () => {
  uni.navigateTo({
    url: '/pages/shareComAI/shareAi'
  })
}
// 页面加载时获取参数
onLoad((options) => {
  if (options?.from === 'bind') {
    pageTitle.value = '绑定手机号'
  }
})

// 发送验证码
const sendCode = async () => {
  // 验证手机号
  if (!form.value.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }

  if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  try {
    // 发送验证码
    const res = await uni.request({
      url: `${API_BASE_URL}/api/sms/code/`,
      method: 'POST',
      data: {
        phone: form.value.phone,
        code_type:'register'
      }
    })

    if (res.statusCode === 200) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })

      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送验证码失败，请重试',
      icon: 'none'
    })
  }
}

// 验证码登录
const handleSubmit = async () => {
  if (!form.value.phone || !form.value.code) {
    uni.showToast({
      title: '请输入手机号和验证码',
      icon: 'none'
    })
    return
  }

  try {
    const res = await uni.request({
      url: `${API_BASE_URL}/api/login/`,
      method: 'POST',
      data: {
        phone: form.value.phone,
        code: form.value.code
      }
    })
    const data=res.data as PhoneParams
    if (res.statusCode === 200 && data) {
      const userStore = useUserStore()
      console.log(res.data,11111)
      // 更新用户信息
    userStore.setUserInfo({
      id: data.user_id,
      phone: data.phone,
      access_token: data.access,
      refresh_token: data.refresh,
      nickname: data.nickname,
      is_wechat_bound: data.is_wechat_bound,
    })

      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })

      // 延迟跳转
      setTimeout(() => {
        uni.switchTab({ url: '/pages/home/home' })
      }, 1500)
    } else {
      // throw new Error(res.data?.message || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    uni.showToast({
      // title: error.message || '登录失败，请重试',
      icon: 'none'
    })
  }
}

const bindTap=()=>{
  console.log('绑定手机号')

}
</script>

<style lang="scss" scoped>
.login-container {
  padding: 40rpx;

  .login-header {
    margin-bottom: 80rpx;

    .title {
      font-size: 48rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .login-form {
    .form-item {
      margin-bottom: 40rpx;

      .input {
        height: 100rpx;
        border: 1px solid #eee;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 32rpx;
      }
    }

    .code-item {
      display: flex;
      align-items: center;

      .input {
        flex: 1;
        margin-right: 20rpx;
      }

      .code-btn {
        width: 200rpx;
        height: 100rpx;
        line-height: 100rpx;
        background: #f8f8f8;
        color: #38b6ff;
        border: none;
        border-radius: 8rpx;
        font-size: 28rpx;

        &[disabled] {
          color: #999;
        }
      }
    }

    .submit-btn {
      margin-top: 60rpx;
      height: 100rpx;
      line-height: 100rpx;
      background: linear-gradient(to right, #38b6ff, #00e5ff);
      color: #fff;
      border-radius: 8rpx;
      font-size: 32rpx;
    }
  }
}
</style>
